/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mygame.Player;

import java.util.ArrayList;
import mygame.Backbone.GlobalVars;
import mygame.Object.GameObject;

/**
 *
 * @author Mr.N0I3oDy
 */
public class Inventory {

    private ArrayList<Ressource> ressources;

    public Inventory() {
        ressources = new ArrayList<Ressource>();
    }

    public void addRessource(GameObject object, int count) {
        boolean exists = false;
        int x;
        for (x = 0; x < ressources.size(); x++) {
            if (ressources.get(x).getObject().equals(object.getRessource())) {
                exists = true;
                break;
            }
        }
        if (!exists) {
            ressources.add(new Ressource(object, count));
        } else {
            ressources.get(x).increaseCount(count);
        }
    }

    public boolean useRessource(String name, int count, boolean check) {
        for (Ressource r : ressources) {
            if (r.getObject().equals(name)) {
                if (check) {
                    if (r.getCount() >= count) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    if (this.decreaseRessource(r, count)) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }
        return false;
    }

    //TODO
    //BETTER CREATE RESSOURCE STRING HERE
    public ArrayList<Ressource> getRessources() {
        return this.ressources;
    }

    public String save() {
        String save = "";
        for (Ressource r : this.ressources) {
            save += GlobalVars.DELIMITER_OBJECTS;
            save += r.getObject();
            save += ",";
            save += r.getCount();
        }
        return save;
    }

    public void load(String l) {
        String[] objs = l.split(GlobalVars.DELIMITER_OBJECTS);
        for (String ll : objs) {
            if (!ll.equals("")) {
                String[] atr = ll.split(",");
                this.ressources.add(new Ressource(atr[0], Integer.parseInt(atr[1])));
            }
        }
    }

    private boolean decreaseRessource(Ressource r, int count) {
        boolean res = r.decreaseCount(count);
        if (res) {
            if (r.getCount() == 0) {
                this.ressources.remove(r);
            }
            return true;
        } else {
            return false;
        }
    }
}
